﻿<template>
  <info-card title="商品信息" ref="cardRef">
    <template #right>
      <el-button type="primary" link @click="exampleShow = true">
        查看示例 <base-icon name="iconfont ic-xiajiantou1" :size="16" />
      </el-button>
    </template>
    <el-form ref="infoFormRef" :model="infoForm" :rules="formRule" label-width="auto">
      <el-form-item label="商品名称" prop="productName">
        <el-input
          v-model="infoForm.productName"
          placeholder="请输入商品名称"
          :style="{ width: '433px' }"
          :maxlength="50"
        >
          <template #suffix>
            <div>
              <span class="text-black">{{ infoForm.productName.length }}</span>
              /
              <span class="text-gray">50</span>
            </div>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="租售类型" prop="rentSaleType">
        <el-radio-group v-model="infoForm.rentSaleType">
          <el-radio
            v-for="item in getConfig('qingyun.product.rent.sale.type')"
            :key="item.dictValue"
            :value="item.dictValue"
            >{{ item.dictLabel }}</el-radio
          >
        </el-radio-group>
      </el-form-item>
      <el-form-item label="商品类型" prop="productType">
        <el-radio-group v-model="infoForm.productType">
          <el-radio
            v-for="item in getConfig('qingyun.product.product.type')"
            :key="item.dictValue"
            :value="item.dictValue"
            >{{ item.dictLabel }}</el-radio
          >
        </el-radio-group>
      </el-form-item>
      <el-form-item label="新旧成色" prop="newOldDegree" v-if="infoForm.productType === '2'">
        <el-radio-group v-model="infoForm.newOldDegree">
          <el-radio
            v-for="item in getConfig('qingyun.product.new.old.degree')"
            :key="item.dictValue"
            :value="item.dictValue"
            >{{ item.dictLabel }}</el-radio
          >
        </el-radio-group>
      </el-form-item>
      <el-form-item label="商品标签" prop="labelList">
        <el-input-tag
          v-model="infoForm.labelList"
          placeholder="请输入租赁标签自定义，可支持多个"
          aria-label="请输入租赁标签自定义，可支持多个"
          :style="{ width: '433px' }"
        />
      </el-form-item>
      <el-form-item label="商品图片" prop="imageUrlList">
        <div class="file-count">
          (<span class="file-count-current">{{ infoForm.imageUrlList.length }}</span
          >/<span>9</span>)
        </div>
        <info-upload v-model="infoForm.imageUrlList" :max="9" />
        <div class="file-desc">1.请上传至少1张商品图片，展示于商品详情顶部轮播区域。</div>
        <div class="file-desc">2. 图片支持png、jpg、jpeg格式；建议单图请小于10M。</div>
      </el-form-item>
      <el-form-item label="商品视频" prop="videoUrl">
        <div class="file-count">
          (<span class="file-count-current">{{ infoForm.videoUrl.length ? 1 : 0 }}</span
          >/<span>1</span>)
        </div>
        <info-upload v-model="infoForm.videoUrl" upload-type="video" upload-text="上传视频" />
        <div class="file-desc">1. 请上传视频，展示于商品轮播图区域。。</div>
        <div class="file-desc">2. 图片支持avi/mp4格式；单视频大小请小于10M。</div>
      </el-form-item>
      <el-form-item label="商品详情" prop="productDetail">
        <div class="relative w-full max-w-[1200px] overflow-hidden rounded-[8px] border border-[var(--cb1)]">
          <div v-if="uploading" class="absolute inset-0 z-10 flex items-center justify-center bg-white/60">
            <el-progress :percentage="progress" type="circle" :width="96" :color="progressColor" />
          </div>
          <Toolbar :editor="editorRef" :default-config="toolbarCfg" mode="default" />
          <Editor
            v-model="infoForm.productDetail"
            :default-config="editorCfg"
            :style="{ height: '360px' }"
            mode="default"
            @on-created="handleEditorCreated"
            @on-change="handleEditorChange"
          />
        </div>
      </el-form-item>
      <el-form-item label="商品参数" prop="productParameterList">
        <!-- 新增参数 -->
        <div class="params-add">
          <el-input placeholder="请输入名称" v-model="addParams.parameterName" :maxlength="10">
            <template #suffix>
              <div>
                <span class="text-black">{{ addParams.parameterName.length }}</span>
                /
                <span class="text-gray">10</span>
              </div>
            </template>
          </el-input>
          <span class="params-add-coln">:</span>
          <el-input placeholder="请输入规格" v-model="addParams.parameterValue" :maxlength="50">
            <template #suffix>
              <div>
                <span class="text-black">{{ addParams.parameterValue.length }}</span>
                /
                <span class="text-gray">50</span>
              </div>
            </template>
          </el-input>
          <el-button class="add-btn" @click="addNewParams">确定添加</el-button>
        </div>
        <!-- 参数列表 -->
        <div class="params-list" v-if="infoForm.productParameterList.length">
          <el-row :gutter="32">
            <el-col :span="24">已添加商品参数</el-col>
            <el-col
              :span="8"
              v-for="(paramsItem, index) in infoForm.productParameterList"
              :key="index"
              class="params-add mr-b"
            >
              <el-input placeholder="请输入名称" v-model="paramsItem.parameterName" :maxlength="10">
                <template #suffix>
                  <div>
                    <span class="text-black">{{ paramsItem.parameterName.length }}</span>
                    /
                    <span class="text-gray">50</span>
                  </div>
                </template>
              </el-input>
              <span class="params-add-coln">:</span>
              <el-input placeholder="请输入规格" v-model="paramsItem.parameterValue" :maxlength="50">
                <template #suffix>
                  <div>
                    <span class="text-black">{{ paramsItem.parameterValue.length }}</span>
                    /
                    <span class="text-gray">50</span>
                  </div>
                </template>
              </el-input>
              <div class="params-del" @click="delParams(index)">
                <base-icon name="iconfont ic-cuowu" :size="14" :color="'var(--ct4)'" />
              </div>
            </el-col>
          </el-row>
        </div>
      </el-form-item>
      <el-form-item label="商品配件" prop="productComponentList">
        <el-button class="add-btn" @click="handleShowComponent">选择配件</el-button>
        <el-table
          :data="infoForm.productComponentList"
          style="width: 100%; margin-top: 12px"
          :header-cell-style="{ 'background-color': 'var(--fl1)' }"
        >
          <el-table-column prop="componentType" label="配件类型" width="auto" align="center" min-width="20%" />
          <el-table-column prop="componentName" label="配件名称" width="auto" align="center" min-width="20%" />
          <el-table-column label="配件数量" width="auto" align="center" min-width="20%">
            <template #default="scope">
              <el-input-number
                :controls="false"
                :min="0"
                v-model="infoForm.productComponentList[scope.$index].quantity"
                placeholder="请输入配件数量"
              />
            </template>
          </el-table-column>
          <el-table-column label="配件价值(元)" width="auto" align="center" min-width="20%">
            <template #default="scope">
              <el-input-number
                :controls="false"
                :min="0"
                v-model="infoForm.productComponentList[scope.$index].amount"
                placeholder="请输入配件价值"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="auto" min-width="20%" align="center">
            <template #default="scope">
              <el-popconfirm title="确定要删除配件吗？" @confirm="handleDelComponent(scope.$index)">
                <template #reference>
                  <el-button link type="primary" size="small"> 删除 </el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
          <template #empty>
            <base-empty description="暂无数据" />
          </template>
        </el-table>
      </el-form-item>
      <el-form-item label="增值服务" prop="productAdditionalServicesList">
        <el-button class="add-btn" @click="handleOpenService">选择增值服务</el-button>
        <el-table
          :data="infoForm.productAdditionalServicesList"
          style="width: 100%; margin-top: 12px"
          show-overflow-tooltip
          :header-cell-style="{ 'background-color': 'var(--fl1)' }"
        >
          <el-table-column prop="name" label="增值服务名称" width="auto" align="center" min-width="15%" />
          <el-table-column label="增值服务类型" width="auto" align="center" min-width="15%">
            <template #default="scope">
              {{ typeName(scope.row.type) }}
            </template>
          </el-table-column>
          <el-table-column label="服务价格" width="auto" align="center" min-width="15%">
            <template #default="scope"> ¥{{ scope.row.price }} </template>
          </el-table-column>
          <el-table-column label="是否强制购买" width="auto" align="center" min-width="10%">
            <template #default="scope">
              {{ scope.row.forceFlag === 1 ? "强制购买" : "不强制购买" }}
            </template>
          </el-table-column>
          <el-table-column
            prop="content"
            label="服务内容"
            width="auto"
            align="center"
            min-width="30%"
            :tooltip-formatter="({ row }) => row.content"
          />
          <el-table-column label="操作" width="auto" min-width="10%" align="center">
            <template #default="scope">
              <el-button link type="primary" size="small" @click.prevent="handleDelService(scope.$index)">
                删除
              </el-button>
            </template>
          </el-table-column>
          <template #empty>
            <base-empty description="暂无数据" />
          </template>
        </el-table>
      </el-form-item>
    </el-form>
    <!-- 选择配件 -->
    <choose-component
      :visble="componetVisble"
      :check-list="infoForm.productComponentList"
      @hide="componetVisble = false"
      @confirm-add="confirmAdd"
    />
    <!-- 选择增值服务 -->
    <choose-service
      :visble="serviceVisble"
      :check-list="infoForm.productAdditionalServicesList"
      @hide="serviceVisble = false"
      @confirm="confirmAddService"
    />
    <!-- 查看示例 -->
    <base-dialog v-model="exampleShow" title="查看示例" width="800" destroy-on-close :show-footer="false">
      <img class="example-img" src="@/assets/product/product-example.png" />
    </base-dialog>
  </info-card>
</template>

<script setup>
  import infoCard from "./InfoCard.vue";
  import InfoUpload from "./InfoUpload.vue";
  import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
  import useWangUpload from "@/utils/useWangUpload";
  import ChooseComponent from "./ChooseComponent.vue";
  import ChooseService from "./ChooseService.vue";
  // 卡片Ref
  const cardRef = ref();
  // 详情
  const detail = inject("detail");
  watch(detail, val => {
    init();
  });
  // 表单Ref
  const infoFormRef = ref();
  // 表单
  const infoForm = ref({
    productName: "",
    rentSaleType: "",
    productType: "",
    newOldDegree: "",
    productDetail: "",
    imageUrlList: [],
    videoUrl: [],
    productParameterList: [],
    productComponentList: [],
    productAdditionalServicesList: [],
  });
  // 表单规则
  const formRule = reactive({
    productName: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
    rentSaleType: [{ required: true, message: "请选择租售类型" }],
    productType: [{ required: true, message: "请选择商品类型" }],
    newOldDegree: [{ required: true, message: "请选择新旧成色" }],
    imageUrlList: [{ required: true, message: "请上传商品图片", trigger: "change" }],
    videoUrl: [{ required: false, message: "请上传商品视频", trigger: "change" }],
    productDetail: [
      { required: true, message: "请上传商品视频", trigger: "change" },
      {
        validator: (_r, v, cb) => (hasMeaningfulContent(v) ? cb() : cb(new Error("请输入商品详情"))),
        trigger: ["change", "blur"],
      },
    ],
    productParameterList: [{ required: false, message: "请上传商品视频", trigger: "change" }],
  });
  // 富文本
  const editorRef = ref();
  const toolbarCfg = { excludeKeys: [] };
  const { menuConf, uploading, progress } = useWangUpload({
    imgMaxMB: 10,
    fileMaxMB: 20,
    videoMaxMB: 100,
    isSecretFile: false,
  });
  const editorCfg = { placeholder: "请输入内容…", MENU_CONF: menuConf };
  function hasMeaningfulContent(html) {
    if (!html) return false;
    const div = document.createElement("div");
    div.innerHTML = html;

    // 文字内容
    const text = (div.textContent || "")
      .replace(/[\u00A0\u200B]/g, "") // nbsp/零宽
      .trim();
    if (text.length > 0) return true;

    // 媒体或结构性内容也算有效
    return !!div.querySelector(
      "img,video,audio,iframe,embed,object,canvas,svg,table tr,ul li,ol li,blockquote,pre,code"
    );
  }
  const handleEditorCreated = editor => (editorRef.value = Object.seal(editor));
  // 处理富文本编辑器内容变化，清除验证错误
  const handleEditorChange = () => {
    console.warn(infoFormRef.value);
    // 延迟执行，确保内容已经更新
    nextTick(() => {
      if (infoFormRef.value && hasMeaningfulContent(infoForm.value.productDetail)) {
        infoFormRef.value.clearValidate("productDetail");
      }
    });
  };
  onBeforeUnmount(() => editorRef.value?.destroy?.());
  // 详情初始化
  const init = () => {
    console.warn(detail.value);
    const {
      productName,
      rentSaleType,
      productType,
      newOldDegree,
      imageUrlList,
      videoUrl,
      labelList,
      productDetail,
      productParameterList,
      productComponentRelateList,
      productAdditionalServiceRelateList,
    } = detail.value;
    infoForm.value = {
      productName,
      rentSaleType: `${rentSaleType}`,
      productType: `${productType}`,
      newOldDegree: `${newOldDegree || ""}`,
      productDetail,
      labelList,
      imageUrlList,
      videoUrl: videoUrl ? [videoUrl] : [],
      productParameterList: productParameterList || [],
      productComponentList: productComponentRelateList || [],
      productAdditionalServicesList: productAdditionalServiceRelateList || [],
    };
  };
  // 新增参数
  const addParams = ref({
    parameterName: "",
    parameterValue: "",
  });
  // 配件弹窗
  const componetVisble = ref(false);
  // 查看示例
  const exampleShow = ref(false);
  // 增值服务弹窗
  const serviceVisble = ref(false);
  // 获取配置选项
  const getConfig = inject("getConfig");
  // 列表服务类型
  const typeName = computed(() => item => {
    const currentItem = getConfig("qingyun.support.customer.additionalServices")?.find(el => el.dictValue == item);
    if (currentItem) {
      return currentItem.dictLabel;
    } else {
      return "";
    }
  });
  // 添加参数
  const addNewParams = () => {
    if (addParams.value.parameterName && addParams.value.parameterValue) {
      infoForm.value.productParameterList.push(addParams.value);
      addParams.value = {
        parameterName: "",
        parameterValue: "",
      };
    }
  };
  // 删除参数
  const delParams = idx => {
    infoForm.value.productParameterList.splice(idx, 1);
  };
  // 打开配件弹窗
  const handleShowComponent = () => {
    componetVisble.value = true;
  };
  // 确认添加配件
  const confirmAdd = data => {
    if (data && data.length) {
      infoForm.value.productComponentList = data.map(item => {
        return { ...item, quantity: "", amount: "" };
      });
    }
    componetVisble.value = false;
  };
  // 删除配件
  const handleDelComponent = idx => {
    infoForm.value.productComponentList.splice(idx, 1);
  };
  // 打开增值服务弹窗
  const handleOpenService = () => {
    serviceVisble.value = true;
  };
  // 确认添加增值服务
  const confirmAddService = data => {
    infoForm.value.productAdditionalServicesList = data;
    serviceVisble.value = false;
  };
  // 删除增值服务
  const handleDelService = idx => {
    infoForm.value.productAdditionalServicesList.splice(idx, 1);
  };
  // 表单验证
  const formVerify = () => {
    return infoFormRef.value.validate();
  };
  const getTop = () => {
    return cardRef.value.getTop();
  };
  // 暴露方法
  defineExpose({
    formVerify,
    getTop,
    infoForm,
  });
</script>

<style lang="scss" scoped>
  .text-black {
    color: var(--ct1);
  }
  .text-gray {
    color: var(--ct4);
  }
  .file-count {
    width: 100%;
    color: var(--ct3);
    font-size: 14px;
    .file-count-current {
      color: var(--ct1);
    }
  }
  .file-desc {
    width: 100%;
    font-size: 12px;
    color: var(--ct3);
    height: 20px;
    margin-bottom: 2px;
  }
  .params-add {
    display: flex;
    align-items: center;
    .params-add-coln {
      color: var(--ct2);
      margin: 0 8px;
    }

    .params-del {
      margin-left: 8px;
      cursor: pointer;
    }
  }
  .params-list {
    width: 100%;
    border-radius: 8px;
    border: 1px solid var(--cb1);
    padding: 16px;
    margin-top: 12px;
  }
  .mr-b {
    margin-bottom: 12px;
  }
  .add-btn {
    border: 1px solid var(--bd3);
    color: var(--bd3);
    margin-left: 8px;
  }
  .custom-header {
    background-color: var(--fl1);
  }
  .example-img {
    width: 100%;
  }
</style>
